﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlexiCommerce.Components;
using NUnit.Framework;
using FlexiCommerce.Persistence.NH;
using Rhino.Mocks;
using FlexiCommerce.Engine;
using System.Reflection;
using FlexiCommerce.Configuration;
using System.Configuration;
using FlexiCommerce.Persistence;

namespace FlexiCommerce.Tests.Persistence
{
    public class DatabasePreparingBase : PersistenceAwareBase
    {
        [TestFixtureSetUp]
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
        }
        [TestFixtureTearDown]
        public virtual void TestFixtureTearDown()
        {
            base.DropDatabaseSchema();
            base.CreateDatabaseSchema();
        }

        [SetUp]
        public override void SetUp()
        {
            base.SetUp();
            base.DropDatabaseSchema();
            base.CreateDatabaseSchema();
        }

        protected Definitions.PersistableItem1 CreateAndSaveItem(string name, GenericPersistenceItem parent)
        {
            Definitions.PersistableItem1 item = CreateOneItem<Definitions.PersistableItem1>(0, "nada", parent);
            item.Name = name;
            engine.Persister.Save(item);

            return item;
        }

        protected Definitions.PersistableItem1 CreateRoot(string name)
        {
            Definitions.PersistableItem1 item = CreateAndSaveItem(name, null);
            return item;
        }
        public ISessionProvider CreateSessionProvider()
        {
            MockRepository mocks = new MockRepository();
            ITypeFinder typeFinder = mocks.StrictMock<ITypeFinder>();
            Expect.On(typeFinder).Call(typeFinder.GetAssemblies())
                .Return(new Assembly[] { typeof(Context).Assembly }).Repeat.Any();
            Expect.On(typeFinder).Call(typeFinder.Find(typeof(GenericPersistenceItem)))
                .Return(new Type[] { typeof(Definitions.PersistableItem1), typeof(Definitions.NonVirtualItem) });
            mocks.ReplayAll();

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder((DatabaseSection)ConfigurationManager.GetSection("flexicommerce/database"), typeFinder);

            return new SessionProvider(configurationBuilder, new NotifyingInterceptor(new ItemNotifier()), new Fakes.FakeWebContextWrapper());
        }
    }
}
